Skip to main content

Vue3 Two-Way Binding

It’s just so easy to achieve two-way binding in Vue3, here’s what I’ve experienced just now:

// In parent component
  <Dialogue v-model="visible"></Dialogue>

If you use v-model like this in the parent component, in the Dialogue child component, you will need to use modelValue to read the variable, if you change it to anything else, unfortunately, the binding will failed immediately!

If you want to rename it and address it in your child component accordingly, you have to declare the v-model like this

// In parent component
  <Dialogue v-model:visible="visible"></Dialogue>

Then the renamed variable should work

export default {
  components: {
    Button
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible'],
  setup(props, context) {
    const close = () => {
      context.emit('update:visible', false)
    }
    return {
      close
    }
  }
}